import { RequestMethod } from "../lib/defines";
import { RoomBase } from "../utils/types";


const { obtainMicrophoneAccess, releaseMicrophoneAccess } = RequestMethod

/**
 * 强拆
 *
 * @param app
 */
export default function microphone (app) {
  const { socket, rooms } = app.locals;
  const { userId, username } = socket.handshake.query;

  /**
   * 抢麦
   *
   * 只有在没有 持有者 的时候，才能够抢麦成功
   */
  socket.on(obtainMicrophoneAccess, function obtainMicrophone (room: RoomBase, cb) {
    const member = { userId, username }
    const __room = rooms[room.classId]

    if (!__room.hasSpeaker()) {
      __room.setSpeaker(member)

      /**
       * 发送向 对应的 房间
       */
      socket
        .to(room.classId)
        .emit(obtainMicrophoneAccess, { room, member }, () => {
          cb && cb({ status: 'ok' })
        });
    } else {
      cb && cb({ status: 'reject' })
    }
  });

  /**
   * 释放麦
   *
   * 只有存在 持有者 的时候，才能够释放麦
   */
  socket.on(releaseMicrophoneAccess, function releaseMicrophone (room: RoomBase, cb) {
    const member = { userId, username }
    const __room = rooms[room.classId]

    if (__room.hasSpeaker()) {
      const speaker = __room.getSpeaker()

      if (speaker?.userId === userId) {
        __room.removeSpeaker()
        /**
         * 发送向 对应的 房间
         */
        socket
          .to(room.classId)
          .emit(releaseMicrophoneAccess, { room, member }, () => {
            cb && cb({ status: 'ok' })
          });

        return
      }
    }

    cb && cb({ status: 'reject' })
  });
}
